
package com.microweb.toastmaster.dao.hibernate;

import java.util.List;

import com.microweb.toastmaster.dao.hibernate.BaseDaoHibernate;
import com.microweb.toastmaster.model.Speech;
import com.microweb.toastmaster.dao.SpeechDao;

import org.springframework.orm.ObjectRetrievalFailureException;

public class SpeechDaoHibernate extends BaseDaoHibernate implements SpeechDao {

    /**
     * @see com.microweb.toastmaster.dao.SpeechDao#getSpeechs(com.microweb.toastmaster.model.Speech)
     */
    public List getSpeechs(final Speech speech) {
        return getHibernateTemplate().find("from Speech order by date");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.
        if (speech == null) {
            return getHibernateTemplate().find("from Speech");
        } else {
            // filter on properties set in the speech
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(speech).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Speech.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }*/
    }

    /**
     * @see com.microweb.toastmaster.dao.SpeechDao#getSpeech(Long id)
     */
    public Speech getSpeech(final Long id) {
        Speech speech = (Speech) getHibernateTemplate().get(Speech.class, id);
        if (speech == null) {
            log.warn("uh oh, speech with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Speech.class, id);
        }

        return speech;
    }

    /**
     * @see com.microweb.toastmaster.dao.SpeechDao#saveSpeech(Speech speech)
     */    
    public void saveSpeech(final Speech speech) {
        getHibernateTemplate().saveOrUpdate(speech);
    }

    /**
     * @see com.microweb.toastmaster.dao.SpeechDao#removeSpeech(Long id)
     */
    public void removeSpeech(final Long id) {
        getHibernateTemplate().delete(getSpeech(id));
    }
}
